/**
 * ...
 * @author Thot
 */

function EditorFiche(){}

EditorFiche._instance = null;
EditorFiche.getInstance = function()
{
	if( EditorFiche._instance == null )
		EditorFiche._instance = new EditorFiche();
		
	return EditorFiche._instance;
};

EditorFiche.prototype.autoSave = true;
EditorFiche.prototype.autoSaveTime = 10000;
EditorFiche.prototype.portraitWidth = 100;
EditorFiche.prototype.portraitHeight = 80;
EditorFiche.prototype.portraitId = 1000;
EditorFiche.prototype.landscapeId = 2000;
EditorFiche.prototype.ficheId = -1;
EditorFiche.prototype.saveURLFiche = "";
EditorFiche.prototype.saveURLImage = "";
EditorFiche.prototype.assetsPath = "";
EditorFiche.prototype.uiPath = "";

EditorFiche.prototype._uiTextures = [
	{url:"picker.png",name:"picker"},
	{url:"cross.png",name:"cross"},
	{url:"resize.png",name:"resize"},
	{url:"rotation.png",name:"rotation"},
	{url:'up.png',name:'up'},
	{url:'DPE_0.png',name:'dpe'},
	{url:'GES_0.png',name:'ges'},
];

EditorFiche.prototype._container = null;
//EditorFiche.prototype._addDPEButton = null;
//EditorFiche.prototype._addGESButton = null;
EditorFiche.prototype._rentButton = null;
EditorFiche.prototype._sellButton = null;
EditorFiche.prototype._titeField = null;
EditorFiche.prototype._saveButton = null;
EditorFiche.prototype._textEditor = null;
EditorFiche.prototype._time = 0;
EditorFiche.prototype._data = null;
EditorFiche.prototype._fileReader = null;
EditorFiche.prototype._textureManager = null;
EditorFiche.prototype._ratio = 1;
EditorFiche.prototype._numFiles = 0;

//public init
EditorFiche.prototype.init = function(data)
{
	this._data = data;
	this._initCanvas();
	this._textEditor = new TextEditor();
	this._textEditor.init("texteditor");
	this._elementEditor = new ElementEditorFiche();
	this._elementEditor.init();
	this._initListeners();
	this._initAssets();
	this.changeOrientation();
};

EditorFiche.prototype.changeOrientation = function(event)
{
	var DOMEditor = document.getElementById("editorZone");
	var ratio = this.portraitWidth / this.portraitHeight;
	var background = this._container.getChildByName("ficheBackground");
	var canvas = document.getElementById("canvasEditor"); 
	var value = ( this._portraitButton.checked ) ? this.portraitId : this.landscapeId;
	
	if( background == null )
	{
		background = new tomahawk_ns.Shape();
	}
		
	//landscape
	if( value == this.portraitId )
	{
		ratio = this.portraitWidth / this.portraitHeight;
		canvas.width = AppConstants.BASE_SIZE;
		canvas.height = canvas.width / ratio;
	}
	else
	{
		canvas.height = AppConstants.BASE_SIZE;
		canvas.width = canvas.height / ratio;
	}
	
	canvas.style.marginTop = parseInt(( DOMEditor.offsetHeight - canvas.height ) * 0.5)+'px';
	canvas.style.marginLeft = parseInt(( DOMEditor.offsetWidth - canvas.width ) * 0.5)+'px';
	
	// plain background
	background.name = "ficheBackground";
	background.clear();
	background.beginPath();
	background.fillStyle("white");
	background.fillRect(0,0,100,100);
	background.fill();
	background.width = 100;
	background.height = 100;
	background.scaleX = canvas.width / background.width;
	background.scaleY = canvas.height / background.height;
	background.cacheAsBitmap = true;
	
	//set mouseEnabled to true
	background.mouseEnabled = true;
	
	tomahawk_ns.Stage.getInstance().addChildAt(background,0);
};

EditorFiche.prototype._appReady = function()
{
	var loader = tomahawk_ns.AssetsLoader.getInstance();
	var data = loader.getData();
	var tex = null;
	
	for( var prop in data )
	{
		tex = new tomahawk_ns.Texture();
		tex.name = prop;
		tex.data = data[prop];
		tex.rect = [0,0,data[prop].width,data[prop].height];
		
		tomahawk_ns.AssetsManager.getInstance().addTexture(tex,tex.name);
	}
		
	this._loadData(this._data);
	tomahawk_ns.Stage.getInstance().addEventListener( tomahawk_ns.Event.ENTER_FRAME, this, this._enterFrame );
};

EditorFiche.prototype._progressHandler = function(event)
{
	var loader = event.target;
};

EditorFiche.prototype._initAssets = function()
{
	var usedTextures = this._getUsedTextures();
	var loader = tomahawk_ns.AssetsLoader.getInstance();
	var i = usedTextures.length;
	var obj = null;
	
	loader.addEventListener( tomahawk_ns.Event.COMPLETE, this, this._appReady );
	loader.addEventListener( tomahawk_ns.Event.PROGRESS, this, this._progressHandler );
	
	while( --i > -1 )
	{
		loader.addFile(this.assetsPath + usedTextures[i], usedTextures[i]);
		this._numFiles++;
	}
	
	i = this._uiTextures.length;
	
	while( --i > -1 )
	{
		obj = this._uiTextures[i];
		loader.addFile( this.uiPath + obj.url, obj.name );
		this._numFiles++;
	}
	
	loader.load();
};

EditorFiche.prototype._initCanvas = function()
{
	var canvas = document.getElementById("canvasEditor"); 
	this._container = new tomahawk_ns.Sprite();
	this._container.mouseEnabled = true;
	
	// init tomahawk
	tomahawk_ns.Stage.getInstance().init(canvas);
	tomahawk_ns.Stage.getInstance().addChild(this._container);
};

EditorFiche.prototype._loadData = function()
{
	var data = this._data;
	var container = this._container;
	var dataChild = null;
	var child = null;
	var i = 0;
	var max = data.length;
	var patterns = ["rent","sell"/*,"title","details","price","hook"*/];

	for( i = 0; i < max; i++ )
	{
		dataChild = data[i];
		
		if( dataChild.type == "TransformableBitmap" )
			child = new TransformableBitmap();
		
		if( dataChild.type == "MesureComponent" )
			child = new MesureComponent();
		
		if( dataChild.type == "TransformableText" )
			child = new TransformableText();
		
		if( child == null )
			continue;
			
		child.unserialize(dataChild);
		
		if( patterns.indexOf(child.name) > -1 )
		{
			child.visible = false;
			child.mouseEnabled = false;
		}
		
		if( child.name == "rentFiche" || child.name == "sellFiche" )
			child.allowDelete = true;
		else
			child.allowDelete = false;
		
		container.addChild(child);
	}
};


//save fiche data
EditorFiche.prototype.save = function()
{
	//var orientation = this._orientation;
	var orientation = ( this._portraitButton.checked ) ? this._portraitButton.value : this._landscapeButton.value;
	var url = this.saveURLFiche+"&ficheId="+this.ficheId;
	var child = null;
	var i = 0;
	var max = this._container.children.length;
	var save = new Array();
	var stage = tomahawk_ns.Stage.getInstance();
	var ratio = 150 / stage.getCanvas().width;
	var preview = document.createElement("canvas");
	var context = preview.getContext("2d");
	var str = null;
	
	
	for( i = 0; i < max; i++ )
	{
		child = this._container.children[i];
		save.push(child.serialize());
	}
	
	
	preview.width = 150;
	preview.height = 107;
	//preview.height = preview.width / ( stage.getCanvas().width / stage.getCanvas().height );
	context.scale(ratio,ratio);
	context.drawImage(stage.getCanvas(),0,0);
	
	
	str = JSON.stringify(save);
	
	
	url += "&ficheName="+this._titeField.value;
	url += "&ficheTheme="+this._themeField.value;
	url += "&ficheFormat="+this._formatField.value;
	url += "&goodType="+this._goodTypeField.value;
	url += "&rent="+this._rentField.value;
	url += "&orientation="+orientation;
	
	//url += "&ficheName="+this._titeField.value;
	//url += "&orientation="+orientation;
	
	this.setLoaderVisible(true);
	FicheSaver.onComplete = this._saveComplete.bind(this);
	FicheSaver.save(url,str,preview.toDataURL());
};

//private
EditorFiche.prototype._getUsedTextures = function()
{
	var data = this._data;
	var container = this._container;
	var dataChild = null;
	var i = 0;
	var max = data.length;
	var results = new Array();

	for( i = 0; i < max; i++ )
	{
		dataChild = data[i];

		if( dataChild.type == "TransformableBitmap" && dataChild.textureName != null)
		{
			results.push(dataChild.textureName);
		}
	}
	
	return results;
};

EditorFiche.prototype._enterFrame = function(event)
{
	var curTime = new Date().getTime();
	if( curTime - this._time > this.autoSaveTime )
	{
		if( this.autoSave == true )
			this.save();
			
		this._time = curTime;
	}
	//tomahawk_ns.Stage.getInstance().drawFPS();
};

EditorFiche.prototype._focusHandler = function(event)
{
	if( event.type == tomahawk_ns.Event.FOCUSED || event.type == tomahawk_ns.Event.UNFOCUSED )
	{
		var target = ( event.type == tomahawk_ns.Event.FOCUSED ) ? event.target : null;
		this._textEditor.setCurrentTextField(target);
	}
	
	if( event.type == EditorEvent.SELECT_OBJECT || event.type == EditorEvent.UNSELECT_OBJECT )
	{
		var target = ( event.type == EditorEvent.SELECT_OBJECT ) ? event.target : null;
		if( target != null )
			this._elementEditor.setCurrentElement(target);
	}
};

EditorFiche.prototype._initListeners = function()
{
	var scope = this;
	var callback1 = function(){scope._mouseHandler.apply(scope,arguments);};
	var callback2 = function(){scope.save.apply(scope,arguments);};
	var callback3 = function(){scope.changeOrientation();};
	
	//this._addDPEButton = document.getElementById('addDPE');
	//this._addGESButton = document.getElementById('addGES');
	this._rentButton = document.getElementById('rentButton');
	this._sellButton = document.getElementById('sellButton');
	this._saveButton = document.getElementById('save');
	this._titeField = document.getElementById('ficheTitle');
	this._goodTypeField = document.getElementById('goodType');
	this._rentField = document.getElementById('rent');
	this._themeField = document.getElementById('ficheTheme');
	this._formatField = document.getElementById('ficheFormat');
	this._portraitButton = document.getElementById('portraitBtn');
	this._landscapeButton = document.getElementById('landscapeBtn');
	
	this._container.addEventListener(tomahawk_ns.Event.FOCUSED, this, this._focusHandler,true);
	this._container.addEventListener(tomahawk_ns.Event.UNFOCUSED, this, this._focusHandler,true);
	this._container.addEventListener(EditorEvent.SELECT_OBJECT, this, this._focusHandler,true);
	this._container.addEventListener(EditorEvent.UNSELECT_OBJECT, this, this._focusHandler,true);
	this._container.addEventListener(EditorEvent.USER_IMAGE_ADDED, this, this._addUserImageHandler,true);
	
	//this._addDPEButton.onclick = callback1;
	//this._addGESButton.onclick = callback1;
	this._rentButton.onclick = callback1;
	this._sellButton.onclick = callback1;
	this._saveButton.onclick = callback2; // save
	this._portraitButton.onclick = callback3;
	this._landscapeButton.onclick = callback3;
};

EditorFiche.prototype.showTrick = function()
{
	var el = document.getElementById('trick');
	if( el )
	{
		el.style.display = 'block';
		setTimeout( function()
			{
				el.style.display = 'none';
			},10000
		);
	}
};

EditorFiche.prototype._mouseHandler = function(event)
{
	//centre, par défaut, sélectionné
	var child = null;
	var container = EditorFiche.getInstance()._container;
	var stage  = tomahawk_ns.Stage.getInstance();
	var texture = null;
	var format = new tomahawk_ns.TextFormat();
	var pattern = null;
	
	
	//if( event.target == this._addDPEButton )
	//{
		//child = this._container.getChildByName("dpe");
		//if( child != null )
			//this._container.removeChild(child);
			//
		//child = new MesureComponent();
		//child.name = "dpe";
		//texture = tomahawk_ns.AssetsManager.getInstance().getTextureByAlias('dpe');
		//child.resize( 200, 100 );
		//child.range = MesureComponent.RANGE_DPE;
		//child.setTexture(texture);
		//child.resizeByWidth();
	//}
	//
	//if( event.target == this._addGESButton )
	//{
		//child = this._container.getChildByName("ges");
		//if( child != null )
			//this._container.removeChild(child);
		//
		//child = new MesureComponent();
		//child.name = "ges";
		//texture = tomahawk_ns.AssetsManager.getInstance().getTextureByAlias('ges');
		//child.range = MesureComponent.RANGE_GES;
		//child.resize( 200, 100 );
		//child.setTexture(texture);
		//child.resizeByWidth();
		//
	//}
	
	if( event.target == this._rentButton )
	{
		child = this._container.getChildByName("rentFiche");
		pattern = this._container.getChildByName("rent");
		
		if( child == null )
		{
			if( pattern == null )
			{
				format.size = 30;
				format.textColor = "white";
				child = new TransformableText(format);
				child.init(200,200,150,50);
				child.setText(Localization.getInstance().getLabel("LOUE"));
				child.setTextAlign(tomahawk_ns.TextField.ALIGN_CENTER);
				child.padding = 15;
				child.rotation = -45;
				child.background = true;
				child.backgroundColor = "red";
				child.border = true;
				child.borderColor = "black";
				child.resize(150,50);
				child.autoFocus();
				this.showTrick();
			}
			else
			{
				child = new TransformableText();
				child.unserialize(pattern.serialize());
				child.visible = true;
				child.autoFocus();
			}
		}
		
		child.name = "rentFiche";
		child.allowDelete = true;
		child.visible = true;
	}	
	
	if( event.target == this._sellButton )
	{
		child = this._container.getChildByName("sellFiche");
		pattern = this._container.getChildByName("sell");
		
		if( child == null )
		{
			if( pattern == null )
			{
				format.size = 30;
				format.textColor = "white";
				child = new TransformableText(format);
				child.init(200,200,150,50);
				child.setText(Localization.getInstance().getLabel("VENDU"));
				child.setTextAlign(tomahawk_ns.TextField.ALIGN_CENTER);
				child.padding = 15;
				child.rotation = -45;
				child.background = true;
				child.backgroundColor = "red";
				child.border = true;
				child.borderColor = "black";
				child.resize(150,50);
				child.autoFocus();
				this.showTrick();
			}
			else
			{
				child = new TransformableText();
				child.unserialize(pattern.serialize());
				child.autoFocus();
			}
		}
		
		child.name = "sellFiche";
		child.allowDelete = true;
		child.visible = true;
	}
	
	if( child != null )
	{
		if( child.name == "background" )
		{
			container.addChildAt( child, 0 );
		}
		else
		{
			container.addChild( child );
		}
	}
	
	event.target.blur();
	stage.getCanvas().focus();
};

EditorFiche.prototype.setLoaderVisible = function(value)
{
	if( value == true )
	{
		document.getElementById('loaderImg').style.visibility = 'visible';
	}
	else
	{
		document.getElementById('loaderImg').style.visibility = 'hidden';
	}
};

EditorFiche.prototype._addUserImageHandler = function(event)
{
	var data = event.data.data;
	var fileName = event.data.name;
	this.setLoaderVisible(true);
	ImageFileSaver.onComplete = this._saveComplete.bind(this);
	ImageFileSaver.save(this.saveURLImage+"&ficheId="+this.ficheId,data,fileName);
};

EditorFiche.prototype._saveComplete = function()
{
	this.setLoaderVisible(false);
};






